//
//  PopoverAnimator.m
//  OC-LBWeibo
//
//  Created by 李博 on 15/7/10.
//  Copyright © 2015年 libo. All rights reserved.
//

#import "PopoverAnimator.h"
#import "PopoverPresentationController.h"

@interface PopoverAnimator() <UIViewControllerTransitioningDelegate,UIViewControllerAnimatedTransitioning>
/// 是否展现的标记
@property(nonatomic,assign)BOOL isPresented;

@end

@implementation PopoverAnimator

// 返回负责转场的控制器对象
- (nullable UIPresentationController *)presentationControllerForPresentedViewController:(nonnull UIViewController *)presented presentingViewController:(nonnull UIViewController *)presenting sourceViewController:(nonnull UIViewController *)source
{
    PopoverPresentationController *pc = [[PopoverPresentationController alloc]initWithPresentedViewController:presented presentingViewController:presenting];
    pc.presentFrame = self.presentFrame;
    
    return pc;
}
// 返回提供动画的Modal的对象
- (nullable id<UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(nonnull UIViewController *)presented presentingController:(nonnull UIViewController *)presenting sourceController:(nonnull UIViewController *)source
{
    self.isPresented = YES;
    return self;
    
}
//返回提供 dismissed 动画的对象
- (nullable id<UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(nonnull UIViewController *)dismissed
{
    self.isPresented = NO;
    return self;
}
//动画时长
- (NSTimeInterval)transitionDuration:(nullable id<UIViewControllerContextTransitioning>)transitionContext
{
    return 1.0;
}

///  转场动画实现函数 － 一旦实现此函数，默认的动画失效，所有的动画由程序员提供
- (void)animateTransition:(nonnull id<UIViewControllerContextTransitioning>)transitionContext
{
    //获取目标视图
    NSString *viewKey = self.isPresented ? UITransitionContextToViewKey : UITransitionContextFromViewKey;
    UIView *targetView = [transitionContext viewForKey:viewKey];
    if (targetView == nil) {
        return;
    }
    
    if (self.isPresented) {
        
        //添加到容器视图
        [[transitionContext containerView]addSubview:targetView];
        targetView.layer.anchorPoint = CGPointMake(0.5, 0);
        targetView.transform = CGAffineTransformMakeScale(1.0, 0);
        
        [UIView animateWithDuration:[self transitionDuration:transitionContext] delay:0 usingSpringWithDamping:0.8 initialSpringVelocity:10 options:UIViewAnimationOptionCurveEaseInOut animations:^{
            
            targetView.transform = CGAffineTransformIdentity;
            
        } completion:^(BOOL finished) {
            //动画结束，一定要写
            [transitionContext completeTransition:YES];
        }];
        
    }else {
        [targetView removeFromSuperview];
        //动画结束，一定要写
        [transitionContext completeTransition:YES];
    }
}

@end
